package com.nx.platform.es.common.utils;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;

import java.util.Map;

/**
 * Created by  on 2017/10/11.
 */
public interface ESHelper {

    default UpdateRequest newUpsertRequest(String index, String type, String id, String routing,
                                           Map<String, Object> doc) {
        UpdateRequest request = new UpdateRequest(index, type, id).doc(doc).docAsUpsert(true);
        if (routing != null) {
            request.routing(String.valueOf(routing));
        }
        return request;
    }

    default UpdateRequest newUpdateRequest(String index, String type, String id, String routing,
                                           Map<String, Object> doc) {
        UpdateRequest request = new UpdateRequest(index, type, id).doc(doc).docAsUpsert(false);
        if (routing != null) {
            request.routing(String.valueOf(routing));
        }
        return request;
    }

    default DeleteRequest newDeleteRequest(String index, String type, String id, String routing) {
        DeleteRequest request = new DeleteRequest(index, type, id);
        if (routing != null) {
            request.routing(String.valueOf(routing));
        }
        return request;
    }

    default String convert(ActionRequest request) {
        if (request instanceof UpdateRequest) {
            return convertToJson((UpdateRequest) request);
        } else if (request instanceof DeleteRequest) {
            return convertToJson((DeleteRequest) request);
        }
        return null;
    }

    default String convert(DocWriteResponse response) {
        if (response instanceof DeleteResponse) {
            return convertToJson((DeleteResponse) response);
        } else if (response instanceof UpdateResponse) {
            return convertToJson((UpdateResponse) response);
        }
        return null;
    }

    default String convertToJson(IndexRequest request) {
        return request.toString();
    }

    default String convertToJson(DeleteRequest request) {
        return request.toString();
    }

    default String convertToJson(UpdateRequest request) {
        return request.toString();
    }

    default String convertToJson(DeleteResponse response) {
        return response.toString();
    }

    default String convertToJson(UpdateResponse response) {
        return response.toString();
    }

}
